package cn.yunhe.java.controller;

import cn.yunhe.java.convert.MerchantDetailConvert;
import cn.yunhe.java.convert.MerchantRegisterConvert;
import cn.yunhe.java.dto.MerchantDTO;
import cn.yunhe.java.service.MerchantService;
import cn.yunhe.java.service.SmsService;
import cn.yunhe.java.util.SecurityUtil;
import cn.yunhe.java.util.SevenCowUtil;
import cn.yunhe.java.vo.MerchantDetailVO;
import cn.yunhe.java.vo.MerchantRegisterVO;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.util.PhoneUtil;

import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
@Slf4j
@Api(tags = {"商户服务"},description = "商户服务--描述")
public class MerchantController {

    @Reference
    MerchantService merchantService;

    @Autowired
    SmsService smsService;


    @GetMapping("/merchants/{id}")
    @ApiOperation(value = "查询商户的信息")
    public MerchantDTO queryMerchantById(@PathVariable("id") Long id) {
        MerchantDTO merchantDTO = merchantService.queryMerchantById(id);
        return merchantDTO;
    }

    @GetMapping("/sms")
    public String getSMSCode(@RequestParam String phone) {

        log.info("向手机号:{}发送验证码", phone);
        return smsService.sendSms(phone);
    }

    @ApiOperation("注册商户")
    @ApiImplicitParam(name = "merchantRegisterVo", value = "注册信息",
            required = true,
            dataType = "MerchantRegisterVo",
            paramType = "body")
    @PostMapping("/merchants/register")
    public MerchantRegisterVO registerMerchant(@RequestBody MerchantRegisterVO merchantRegisterVo) {
        //校验验证码
        smsService.checkVerifyCode(
                merchantRegisterVo.getVerifyKey(),
                merchantRegisterVo.getVerifyCode()
        );
        //注册商户
//        MerchantDTO merchantDTO = new MerchantDTO();
//        merchantDTO.setUsername(merchantRegisterVo.getUsername());
//        merchantDTO.setMobile(merchantRegisterVo.getMobile());
//        merchantService.createMerchant(merchantDTO);
        MerchantDTO merchantDTO = MerchantRegisterConvert.INSTANCE.vo2dto(merchantRegisterVo);

        // 1.校验
        if (merchantRegisterVo == null) {
            throw new BusinessException(CommonErrorCode.E_100108);
        }

        //手机号非空校验
        if (StringUtils.isBlank(merchantRegisterVo.getMobile())) {
            throw new BusinessException(CommonErrorCode.E_100112);
        }

        //校验手机号的合法性
        if (!PhoneUtil.isMatches(merchantRegisterVo.getMobile())) {
            throw new BusinessException(CommonErrorCode.E_100109);
        }

        //联系人非空校验
        if (StringUtils.isBlank(merchantRegisterVo.getUsername())) {
            throw new BusinessException(CommonErrorCode.E_100110);
        }

        //验证码非空校验
        if (StringUtils.isBlank(merchantRegisterVo.getVerifyCode()) ||
                StringUtils.isBlank(merchantRegisterVo.getVerifyKey())) {
            throw new BusinessException(CommonErrorCode.E_100103);
        }


        merchantService.createMerchant(merchantDTO);

        return merchantRegisterVo;
    }


    //上传证件照
    @ApiOperation("上传证件照")
    @PostMapping("/upload")
    public String upload(@ApiParam(value = "证件照",required = true) @RequestParam("file") MultipartFile multipartFile) throws BusinessException, IOException {

        // 获取输入流
        InputStream is = multipartFile.getInputStream();

        String originalFilename = multipartFile.getOriginalFilename(); // 上传文件原文件名
        String ext = originalFilename.substring(originalFilename.indexOf(".")); // 截取获取扩展名

        String key = UUID.randomUUID() + ext;

        // 上传文件
        String accessPath = SevenCowUtil.update2Service(is, key);

        return accessPath;
    }



    @ApiOperation("资质申请")
    @PostMapping("/merchants/save")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "merchantInfo"
                    , value = "商户认证资料"
                    , required = true
                    , dataType = "MerchantDetailVO"
                    , paramType = "body")
    })
    public void saveMerchant(@RequestBody MerchantDetailVO merchantInfo){
        //解析token，取出当前登录商户的id
        Long merchantId = SecurityUtil.getMerchantId(merchantService);

        // copy属性到MerchantDTO
        MerchantDTO merchantDTO = MerchantDetailConvert.INSTANCE.vo2dto(merchantInfo);

        // 资质申请
        merchantService.applyMerchant(merchantId,merchantDTO);
    }



}
